In computer programming, array slicing is an operation that extracts a subset of elements from an array and packages them as another array, possibly in a different dimension from the original.
Common examples of array slicing are extracting a substring from a string of characters, the " ell" in "h ello", extracting a row or column from a two-dimensional array, or extracting a vector from a matrix.
Depending on the programming language, an array slice can be made out of non-consecutive elements. Also depending on the language, the elements of the new array may be aliased to (i.e., share memory with) those of the original array.
Reducing the range of any index to a single value effectively removes the need for that index. This feature can be used, for example, to extract one-dimensional slices (vectors in 3D, including rows, columns, and tubes) or two-dimensional slices (rectangular matrices) from a three-dimensional array. However, since the range can be specified at run-time, type-checked languages may require an explicit (compile-time) notation to actually eliminate the trivial indices.
General array slicing can be implemented (whether or not built into the language) by referencing every array through a dope vector or descriptor a record that contains the address of the first array element, and then the range of each index and the corresponding coefficient in the indexing formula. This technique also allows immediate array transpose, index reversal, subsampling, etc. For languages like C, where the indices always start at zero, the dope vector of an array with d indices has at least 1 + 2 d parameters. For languages that allow arbitrary lower bounds for indices, like Pascal, the dope vector needs 1 + 3 d entries.
If the array abstraction does not support true negative indices (as the arrays of Ada and Pascal do), then negative indices for the bounds of the slice for a given dimension are sometimes used to specify an offset from the end of the array in that dimension. In 1-based schemes, -1 generally indicates the second-to-last item, while in a 0-based system, it refers to the very last item.
Kenneth Iverson's APL (1957) had very flexible multi-dimensional array slicing, which contributed much to the language's expressive power and popularity.
ALGOL 68 (1968) introduced comprehensive multi-dimension array slicing and trimming features.
Array slicing facilities have been incorporated in several modern languages, such as Ada, Cobra, D, Fortran, Go, Rust, Julia, MATLAB, Perl, Python, S-Lang, Windows PowerShell and the mathematical/statistical languages GNU Octave, S and R.
DECLARE X(5,5);
DECLARE Y(5) DEFINED(X(1SUB,1SUB));
A reference to Y(2) is a reference to X(2,2), and so on.
DECLARE X(5,5);
X(*,1)=0;
SUBROUTINE PRINT V(VEC, LEN)
REAL VEC(*)
PRINT *, (VEC(I), I = 1, LEN)
END
PROGRAM MAIN
PARAMETER(LEN = 3)
REAL MATRIX(LEN, LEN)
DATA MATRIX/1, 1, 1, 2, 4, 8, 3, 9, 27/
CALL PRINT V(MATRIX(1, 2), LEN)
END
Result:
2.000000 4.000000 8.000000
[lower bound:upper bound] ''¢ for computers with extended character sets ¢''
or:
(LOWER BOUND..UPPER BOUND) ''# FOR COMPUTERS WITH ONLY 6 BIT CHARACTERS. #''
Both bounds are inclusive and can be omitted, in which case they default to the declared array bounds. Neither the stride facility, nor diagonal slice aliases are part of the revised report.
Examples:
[3, 3]real a := ((1, 1, 1), (2, 4, 8), (3, 9, 27)); ''# declaration of a variable matrix #''
[,] real c = ((1, 1, 1), (2, 4, 8), (3, 9, 27)); ''# constant matrix, the size is implied #''
ref[]real row := a[2,]; ''# alias/ref to a row slice #''
ref[]real col2 = a[, 2]; ''# permanent alias/ref to second column #''
print ((a[:, 2], newline)); ''# second column slice #''
print ((a[1⌈a, :], newline)); ''# last row slice #''
print ((a[:, 2⌈a], newline)); ''# last column slice #''
print ((a[:2, :2], newline)); ''# leading 2-by-2 submatrix "slice" #''
+1.000010+0 +4.000010+0 +9.000010+0
+3.000010+0 +9.000010+0 +2.700010+1
+1.000010+0 +8.000010+0 +2.700010+1
+1.000010+0 +1.000010+0 +2.000010+0 +4.000010+0
Example:
Will produce:
Slicing was also selected as the basis for the ANSI Full BASIC standard, using the colon as the separator and thus differentiating between slicing and array access:
While this style of access offered a number of advantages, especially for the small machines of the era, sometime after 1970 Digital Equipment Corporation introduced their own variation of BASIC that used the , and string functions. Microsoft BASIC was written on the PDP-10 and its BASIC was used as the pattern. Through the late 1970s the two styles were both widely used, but by the early 1980s the DEC-style functions were the de facto standard.
ans =
8 3 5 7
8 9 1 4
4 4 2 5
>> A(:, 2:3, 3) % 3x2 two-dimensional array along first and second dimensions
ans =
3 5
9 1
4 2
>> A(2:end, :, 3) % 2x4 two-dimensional array using the 'end' keyword; works with GNU Octave 3.2.4
ans =
6 1 4 6
10 1 3 1
>> A(1, :, 3) % single-dimension array along second dimension
ans =
8 3 5 7
>> A(1, 2, 3) % single value ans = 3
The : operator implements the stride syntax (lower_bound:upper_bound[:stride]) by generating a vector. 1:5 evaluates as [1, 2, 3, 4, 5]. 1:9:2 evaluates as [1, 3, 5, 7, 9]. A bare : evaluates the same as 1:end, with end determined by context.
[, 1] [, 2] [, 3] [, 4]
1, 25 28 31 34
2, 26 29 32 35
3, 27 30 33 36
> A, # 3x2x1 cubic array subset (preserved dimensions)
, , 1
[, 1] [, 2]
1, 28 31
2, 29 32
3, 30 33
> A, # single-dimension array along first dimension
1 28 29 30
> A1, # single value
1 28
PRINT *, 'ABCDE'(2:4)
END
Produces:
PROGRAM MAIN
CHARACTER *(*)STR
PRINT *, STR
END
CALL PRINT S('ABCDE'(2:4))
END
Again produces:
procedure Main is
Text : String := "ABCDE";
begin
Text_IO.Put_Line (Text (2 .. 4));
end Main;
Produces:
Note: Since in Ada indices are n-based the term Text (2 .. 4) will result in an Array with the base index of 2.
The definition for Text_IO.Put_Line is:
procedure Put_Line(Item : in String);
The definition for String is:
subtype Positive is Integer range 1 .. Integer'Last;
type String is array(Positive range <>) of Character;
pragma Pack(String);
As Ada supports true negative indices as in it places no special meaning on negative indices. In the example above the term Some_History_Data (-30 .. 30) would slice the History_Data from 31 Before Christ to 30 Anno Domini (since there was no year zero, the year number 0 actually refers to 1 Before Christ).
Perl supports negative list indices. The -1 index is the last element, -2 the penultimate element, etc. In addition, Perl supports slicing based on expressions, for example:
It is possible to slice by using a notation similar to element retrieval:
print(nums:3) # from index 0 (inclusive) until index 3 (exclusive)
print(nums1:5)
print(nums-3:)
print(nums3::) # == nums3:
print(nums::3) # starting at index 0 and getting every third element
print(nums1:5:2) # from index 1 until index 5 and getting every second element
The stride syntax (nums[1:5:2]) was introduced in the second half of the 1990s, as a result of requests put forward by scientific users in the Python "matrix-SIG" (special interest group).
Slice semantics potentially differ per object; new semantics can be introduced when operator overloading the indexing operator. With Python standard lists (which are ), every slice is a copy. Slices of NumPy arrays, by contrast, are views onto the same underlying buffer.
Both bounds are inclusive and can be omitted, in which case they default to the declared array bounds. Stride defaults to 1. Example:
print *, a(:, 2) ! second column
print *, a(m, :) ! last row
print *, a(:10, :10) ! leading 10-by-10 submatrix
Naming indexes in slicing and subscripting is similar to naming parameters in function calls instead of relying on a fixed sequence of parameters. One advantage of naming indexes in slicing is that the programmer does not have to remember the sequence of Indexes, in a multidimensional array. A deeper advantage is that expressions generalize automatically and safely without requiring a rewrite when the number of dimensions of X changes.
Suppose that A is a 1-d array such as
A = [1:50]; % A = [1, 2, 3, ...49, 50]
Then an array B of first 5 elements of A may be created using
B = A[[:4]];
Similarly, B may be assigned to an array of the last 5 elements of A via:
B = A[[-5:]];
Other examples of 1-d slicing include:
A[-1] % The last element of A
A[*] % All elements of A
A[[::2]] % All even elements of A
A[[1::2]] % All odd elements of A
A[[-1::-2]] % All even elements in the reversed order
A[[[0:3], [10:14]]] % Elements 0-3 and 10-14
Slicing of higher-dimensional arrays works similarly:
A[-1, *] % The last row of A
A[[1:5], [2:7]] % 2d array using rows 1-5 and columns 2-7
A[[5:1:-1], [2:7]] % Same as above except the rows are reversed
Array indices can also be arrays of integers. For example, suppose that I = [0:9] is an array of 10 integers. Then A[I] is equivalent to an array of the first 10 elements of A. A practical example of this is a sorting operation such as:
I = array_sort(A); % Obtain a list of sort indices
B = A[I]; % B is the sorted version of A
C = A[array_sort(A)]; % Same as above but more concise.
Take a slice out of it:
and the contents of b will be [7, 3, 8]. The first index of the slice is inclusive, the second is exclusive.
means that the dynamic array c now contains [8, 6] because inside the the $ symbol refers to the length of the array.
D array slices are aliased to the original array, so:
means that a now has the contents [2, 5, 7, 3, 10, 6, 4, 1]. To create a copy of the array data, instead of only an alias, do:
Unlike Python, D slice bounds don't saturate, so code equivalent to this Python code is an error in D:
a0, 3 = 100, // replace the first and the fourth element of a
a2.. = 100, // replace the two last elements of a
// assign a multidimensional array to the variable a
a = [0,, 5,, 10,, 15,];
a.slice(2, 3); // take a slice with coordinates 2 and 3 (returns 13)
a.slice(nil, 3); // take an orthogonal slice (returns 3,)
> echo $A(seq # Print the first two elements of $A 3 5
> set B $A1 # $B contains the first and second element of $A, i.e. 3, 5
> set -e A$B; echo $A # Erase the third and fifth elements of $A, print $A 3 5 9
then the first 3 elements, middle 3 elements, and last 3 elements would be:
Cobra also supports slicing-style syntax for 'numeric for loops':
for j in 3
print i
print j
then the first 3 elements, middle 3 elements, last 3 elements, and a copy of the entire slice would be:
Slices in Go are reference types, which means that different slices may refer to the same underlying array.
Cilk Plus's array slicing differs from Fortran's in two ways:
julia> x:, # get the second column.
4-element Array{Float64,1}:
julia> x1, # get the first row.
1x3 Array{Float64,2}:
julia> x1:2,2:3 # get the submatrix spanning rows 1,2 and columns 2,3
2x2 Array{Float64,2}:
0.323877 0.186253 0.600605
0.404664 0.894781 0.0955007
0.223562 0.18859 0.120011
0.149316 0.779823 0.0690126
0.186253
0.894781
0.18859
0.779823
0.323877 0.186253 0.600605
0.186253 0.600605
0.894781 0.0955007
One way is the class System.ArraySegment. There is also the class System.Span, which allows for stack-allocated arrays or string slicing.
// ...
int a = 1,;
// using an ArraySegment
ArraySegment
// using a Span
Span
using std::span; using std::vector;
// ...
vector
// Creates a span using index 2, taking 4 elements
span
// Creates a span over the whole vector and then takes a subspan beginning
// at index 2, taking 4 elements
span
|
|